<template>
    <div class="table-all">
        <!-- 搜索区 -->
        <div class="app-container search-box">
            <SearchForm
                    :form="searchData.form"
                    :options="searchData.options"
                    @searchUpdate="search"
                    @resetSearchData="resetSearchData"
            ></SearchForm>
        </div>
        <!-- 按钮区 -->
        <div class="app-container table-box">
            <div class="table-main">
                <!-- 表格 -->
                <v-table
                        title="隐患上报数据"
                        v-if="tableMainHeight>0"
                        :table-columns="tableColumns"
                        :table-data="tableData"
                        :loading="loading"
                        :is-index="true"
                        ref="table"
                        :maxHeight="tableMainHeight">
                    <template #topButtonList>
                        <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
                    </template>
                    <template #state="scope">
                      {{getDictValue(scope.row.state, stateOptions)}}
                    </template>
                    <template #bclassify="scope">
                      {{getDictValue(scope.row.bclassify, bClassifyOptions)}}
                    </template>
                    <template #sclassify="scope">
                      {{$commonJs.getRiskHazardLabelName(scope.row.bclassify, scope.row.sclassify, hazardBClassifyList)}}
                      <!--{{getDictValue(scope.row.sclassify, sClassifyOptions)}}-->
                    </template>
                    <template #category="scope">
                      {{getDictValue(scope.row.category, categoryOptions)}}
                    </template>
                    <template #grade="scope">
                      {{getDictValue(scope.row.grade, gradeOptions)}}
                    </template>

                    <template #superviseState="scope">
                      {{getDictValue(scope.row.superviseState, superviseStateOptions)}}
                    </template>

                    <template #operation="scope">
                      <div v-if="scope.row.state==2||scope.row.state==3" style="text-align: center">
                        <a v-hasPermission="['riskHazard:detail']" class="table-btn-view table-operation"
                           @click="detail(scope.row)">{{$t('table.view')}}</a>
                      </div>
                      <div v-else>
                        <a v-hasPermission="['riskHazard:add']" class="table-btn-edit table-operation"
                           @click="handleEdit(scope.row)">{{$t('table.edit')}}</a>

                        <a v-hasPermission="['riskHazard:detail']" class="table-btn-view table-operation"
                           @click="detail(scope.row)">{{$t('table.view')}}</a>
                        <span v-if="scope.row.superviseOrderNum==null||scope.row.superviseOrderNum==''" >
                          <a v-hasPermission="['riskHazard:orderPush']" class="table-btn-view table-operation"
                             @click="supervise(scope.row)">{{$t('table.urge')}}</a>
                        </span>

                        <a v-hasPermission="['riskHazard:delete']" class="table-btn-delete table-operation"
                           @click="singleDelete(scope.row)">{{$t('table.delete')}}</a>

                      </div>
                    </template>
                </v-table>
            </div>
            <div class="table-page">
                <!-- 页码 -->
                <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                            @pagination="search"/>
            </div>
        </div>
        <!-- 详情 -->
        <detailDialog :dialog-visible="detailDialogShow"
                    @success="editSuccess"
                    @close="editClose"
                    :openType="detailOpenType"
                    :id="detailId"
                    :title="detailTitle"
        ></detailDialog>

      <!-- 归档详情 -->
      <detailEndDialog :dialog-visible="detailEndDialogShow"
                    @success="editSuccess"
                    @close="editClose"
                    :openType="detailOpenType"
                    :superviseOrderNum="curSuperviseOrderNum"
                    :id="detailId"
                    :title="detailTitle"
      ></detailEndDialog>

        <tableImportDialog
          ref="importDialog"
          :dialog-visible.sync="importDialog.isVisible"
          :title="importDialog.title"
          :template-list="importTemplateList"
          :uploadOptions="uploadOptions"
        />
    </div>
</template>

<script>
    import { riskHazardPage,
            riskHazardExport,
            riskHazardDelete,orderPush } from '@/api/risk/riskHazard'
    import SearchForm from '@/components/searchForm/index'
    import ButtonForm from '@/components/ButtonForm/index'
    import VTable from '@/components/VTable/index'
    import Pagination from '@/components/Pagination/index'
    import detailDialog from './detail.vue'
    import detailEndDialog from '../hazardEnd/detail.vue'
    import tableImportDialog from '@/components/TableImportDialog/tableImportDialog'
    import { treeDataList} from '@/api/risk/treeData'
    export default {
        components:{
            VTable,Pagination,detailDialog,SearchForm,ButtonForm,tableImportDialog,detailEndDialog
        },
        data(){
            return{
              hazardBClassifyList:[],
              importDialog:{
                isVisible: false,
                title: '风险隐患上报'
              },
              importTemplateList: [
                {
                  label: '下载导入模板',
                  url: '/risk/riskHazard/template',
                  downloadFileName: '风险隐患上报.xlsx',
                  // clickFn: this.downloadTemplate, //选填项，点击下载按钮时触发，如果想自己手动实现下载，可在这里定义方法，否则使用默认的下载方法
                },
              ],
              uploadOptions: {
                accept: '.xlsx', //限制文件格式，多个用逗号隔开如：'.xlsx,.png'
                uploadTextTip: '请上传excel文件,以.xlsx为后缀',
                url: '/risk/riskHazard/import',
                // uploadFn: this.handleUpload, //选填项，点击确认时触发上传，如果想自己手动实现上传，可在这里定义方法，否则使用默认的上传方法
                successFn: this.handleUploadSuccess, //选填项，上传成功后触发
              },

                tableColumns:[
                            // {
                            //     prop: 'flagCode',
                            //     label: '标识码',
                            //     minWidth: '100',
                            //     slotname: 'flagCode',
                            //     options: {}
                            // },
                            {
                              prop: 'projectName',
                              label: '所属工地',
                              minWidth: '150',
                              slotname: 'projectName',
                              options: {}
                            },
                            {
                                prop: 'name',
                                label: '风险隐患名称',
                                minWidth: '150',
                                slotname: 'name',
                                options: {}
                            },

                            {
                                prop: 'bclassify',
                                label: '风险隐患大类',
                                minWidth: '150',
                                slotname: 'bclassify',
                                options: {}
                            },
                            {
                                prop: 'sclassify',
                                label: '风险隐患细类',
                                minWidth: '150',
                                slotname: 'sclassify',
                                options: {}
                            },

                            {
                              prop: 'grade',
                              label: '风险隐患等级',
                              minWidth: '150',
                              slotname: 'grade',
                              options: {}
                            },

                            {
                              prop: 'state',
                              label: '状态',
                              minWidth: '80',
                              slotname: 'state',
                              options: {}
                            },




                            {
                                prop: 'address',
                                label: '风险隐患地址',
                                minWidth: '150',
                                slotname: 'address',
                                options: {}
                            },




                            {
                                prop: 'reportName',
                                label: '上报人',
                                minWidth: '150',
                                slotname: 'reportName',
                                options: {}
                            },

                            {
                              prop: 'reportContact',
                              label: '上报人联系方式',
                              minWidth: '150',
                              slotname: 'reportContact',
                              options: {}
                            },

                            {
                              prop: 'finishTimeState',
                              label: '按时完成整改',
                              minWidth: '150',
                              slotname: 'finishTimeState',
                              options: {}
                            },
                            {
                              prop: 'superviseState',
                              label: '督办状态',
                              minWidth: '100',
                              slotname: 'superviseState',
                              options: {}
                            },

                    {
                        prop: 'operation',
                        label: '操作',
                        width: '210rem',
                        align: 'center',
                        slotname: 'operation',
                        overflow: false,
                        fixed: 'right'
                    }
                ],
                tableData:[],
                selection: [],
                loading:false,
                total:1,
                pageNum:1,
                pageSize:10,
                detailOpenType:"add",
                detailDialogShow:false,
                detailEndDialogShow:false,
                detailId:"",
                curSuperviseOrderNum:"",
                detailTitle:"新增",
                dict:{},
                searchData:{
                  form:{
                        state:'',
                        name:'',
                        bclassify:'',
                        address:'',
                        finishTimeState:'',
                },
                  options:[
                             {
                               title:'隐患状态',
                               key: "state",
                               type: "select",
                               multiple:false,
                               option: {
                                 data: this.stateOptions,
                                 props: {
                                   key: "id", // 指定key对应data的字段
                                   label: "label", // 指定label对应data的字段
                                   value: "value", // 指定value对应data的字段
                                 },
                               },
                             },
                             {
                                 title:'风险隐患名称',
                                 key: "name",
                                 type: "text",
                             },

                             {
                                 title:'风险隐患地址',
                                 key: "address",
                                 type: "text",
                             },
                             {
                               title:'风险隐患大类',
                               key: "bclassify",
                               type: "select",
                               multiple:false,
                               option: {
                                 data: this.bClassifyOptions,
                                 props: {
                                   key: "id", // 指定key对应data的字段
                                   label: "label", // 指定label对应data的字段
                                   value: "name", // 指定value对应data的字段
                                 },
                               },
                             },
                              {
                                title:'按时完成整改',
                                key: "finishTimeState",
                                type: "select",
                                multiple:false,
                                option: {
                                  data: this.finishTimeStateOptions,
                                  props: {
                                    key: "id", // 指定key对应data的字段
                                    label: "label", // 指定label对应data的字段
                                    value: "name", // 指定value对应data的字段
                                  },
                                },
                              },

                   ]
                },
                buttonList:[
                    {name:'新增',methods:'handleAdd',type:'primary',haspremission:['riskHazard:add']},

                    // {name:'导入',methods:'handleImport'},
                    // {name:'导出',methods:'handleExport'}
                ],
                tableMainHeight: 0,
                // 字典
                stateOptions:[],
                bClassifyOptions:[],
                bSlassifyOptions:[],
                categoryOptions:[],
                gradeOptions:[],
                finishTimeStateOptions:[],
                superviseStateOptions:[],
            }
        },
        watch: {
            // 字典
          'superviseStateOptions':{
            handler(newVal, oldVal) {
              this.searchData.options.forEach(t=>{
                if(t.key=='superviseState'){
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },


          'stateOptions':{
              handler(newVal, oldVal) {
                this.searchData.options.forEach(t=>{
                  if(t.key=='state'){
                    t.option.data = newVal
                  }
                })
              },
              deep: true,
              immediate: true
            },

            'bClassifyOptions':{
                handler(newVal, oldVal) {
                    this.searchData.options.forEach(t=>{
                        if(t.key=='bclassify'){
                        t.option.data = newVal
                    }
                })
                },
                deep: true,
                immediate: true
            },

            'sClassifyOptions':{
              handler(newVal, oldVal) {
                this.searchData.options.forEach(t=>{
                  if(t.key=='sclassify'){
                    t.option.data = newVal
                  }
                })
              },
              deep: true,
              immediate: true
            },

          'categoryOptions':{
            handler(newVal, oldVal) {
              this.searchData.options.forEach(t=>{
                if(t.key=='category'){
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },

          'gradeOptions':{
            handler(newVal, oldVal) {
              this.searchData.options.forEach(t=>{
                if(t.key=='grade'){
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },

          'finishTimeStateOptions':{
            handler(newVal, oldVal) {
              this.searchData.options.forEach(t=>{
                if(t.key=='finishTimeState'){
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },


        },
        methods:{
            //跳转到详情页
            detail(row){
              this.detailEndDialogShow=true;
              this.detailId = row.id;
              this.detailTitle = "详情";
              this.detailOpenType="detail";
              this.curSuperviseOrderNum= row.superviseOrderNum
            },
            // 判断流程是否结束(归档)
            checkStateEnd(value){
              if (value == 3) {
                return true;
              }
              return false;
            },

            // 判断是否显示图片
            checkImgShow(value){
              if (value == null || value == '' || value=='null') {
                return false;
              }
              let img = JSON.parse(value)
              return img.length > 0 ? true : false
            },
            // 格式化图片值
            getImgFormatValue(value, type){
              let img = JSON.parse(value)
              if(type=='url'){
                // 只显示第一张
                return process.env.VUE_APP_BASE_API + 'file/api/download/'+ img[0].fileId
              }
              if(type=='list'){
                return img.map(t=>{ return process.env.VUE_APP_BASE_API + 'file/api/download/'+ t.fileId})
                // return [process.env.VUE_APP_BASE_API + 'file/api/download/'+ img[0].fileId]
              }
            },
            handleDownload(data){
              let fileName = "风险隐患上报导入模板.xlsx"
              return riskSourceTemplate(data, fileName)
            },
            handleUpload(file){
              // console.log("file",file)
              const formData = new FormData()
              formData.append('file', file)
              //   formData.append('file', fileList[0].raw)
              //   console.log("formData,==",formData.get("file"))
              riskShelterImport(formData)
                .then((res) => {
                  if (res.code === 200) {
                    this.$message.success('导入成功')
                    this.search()
                    this.importDialog.isVisible = false
                  }
                })
                .finally(() => {
                  this.$refs.importDialog.clearFileList()
                })
            },
            handleUploadSuccess(){
              this.search()
              this.importDialog.isVisible = false
            },
            handleClose() {
              this.importDialog.isVisible = false
            },

            getCheckBoxValue(value,option){
                if(!value){
                    return
                }
                let temp = []
                let data = value.split(",")
                data.forEach(t=>{
                    let item = option.find(x=> x.value == t)
                if(item != undefined){
                    temp.push(item.label)
                }
            })
                return temp.join(",")
            },
            getDictValue(value,option){
                let item = option.find(t=> t.value == value)
                if(item!=undefined){
                    return item.label
                }
                return value
            },
            editClose(){
                this.detailDialogShow = false
                this.detailEndDialogShow = false
            },
            editSuccess(){
                this.search()
                this.detailDialogShow = false
                this.detailEndDialogShow = false
            },
            search(){
                this.fetch({
                        ...this.searchData.form,
                })
            },
            fetch(params={}){
                params.pageSize = this.pageSize
                params.pageNum = this.pageNum
                console.log("user.deptIds:",this.$store.state.account.user.deptIds);
                //params.processState='1';
                //params.areaCode = this.$store.state.account.user.deptIds

                this.loading = true
                 riskHazardPage(params).then(res=>{
                    if(res.code==200){
                        this.total = res.data.total
                        this.tableData = res.data.rows
                    }else{
                    this.$message({
                        message: this.$t('tips.systemException'),
                        type: 'error'
                     })
                   }
                }).finally(final=>{
                    this.loading = false
               })
            },
            // 重置搜索条件
            resetSearchData(){
                this.searchData.form = {
                        name:'',
                        bclassify:'',
                        address:'',
                        processState:'',
                        finishTimeState:''
                }
            },

            // 触发按钮区域按钮方法
            clickButton(methods){
                this[methods]()
            },
            handleAdd(){
                this.detailOpenType = "add"
                this.detailTitle = "新增"
                this.detailDialogShow = true
            },
            handleEdit(row){
                this.detailId = row.id
                this.detailOpenType = "edit"
                this.detailTitle="编辑"
                this.detailDialogShow = true
            },

            supervise(row){
              this.$confirm('确定督办？', this.$t('common.tips'), {
                confirmButtonText: this.$t('common.confirm'),
                cancelButtonText: this.$t('common.cancel'),
                type: 'warning'
              }).then(() => {
                this.loading = true
                var param = {};
                param.orderNum = row.id;
                var backData ={};
                backData.type='1';
                param.backData = JSON.stringify(backData);
                orderPush(param).then(res=>{
                  if(res.code==200){
                    this.$message({
                      message: '督办提交成功',
                      type: 'success'
                    })
                    this.search()
                  }else{
                    this.$message({
                      message: this.$t('tips.systemException'),
                      type: 'error'
                    })
                  }
                }).finally(final=>{
                  this.loading = false
                })
              })
            },

            handleExport(){
                let params = {
                        ...this.searchData.form
                }
                riskHazardExport(params,`风险隐患上报_${new Date().getTime()}.xlsx`);
            },
            handleImport(){
              console.log("等待处理")
              this.importDialog.isVisible = true
            },


            closeDialog(){
              this.detailDialogShow = false
            },

            singleDelete(row){
                this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
                    confirmButtonText: this.$t('common.confirm'),
                    cancelButtonText: this.$t('common.cancel'),
                    type: 'warning'
                }).then(() => {
                    this.loading = true
                    riskHazardDelete(row.id).then(res=>{
                    if(res.code==200){
                    this.$message({
                        message: this.$t('tips.deleteSuccess'),
                        type: 'success'
                    })
                    this.search()
                     }else{
                        this.$message({
                            message: this.$t('tips.systemException'),
                            type: 'error'
                        })
                    }
                 }).finally(final=>{
                    this.loading = false
                 })
                })
            }
        },
        activated(){
            this.fetch()
        },
        created(){
            // 获取字典值

          this.stateOptions = []
          this.$commonJs.filterDataDict("hazardDealState",this.stateOptions )


          this.bClassifyOptions = []
          this.$commonJs.filterDataDict("hazardBClassify",this.bClassifyOptions )

          this.sClassifyOptions = []
          this.$commonJs.filterDataDict("hazardSClassify",this.sClassifyOptions )

          this.categoryOptions = []
          this.$commonJs.filterDataDict("hazardCategory",this.categoryOptions )

          this.gradeOptions = []
          this.$commonJs.filterDataDict("patrolHazardLevel",this.gradeOptions )

          this.finishTimeStateOptions = [{"name":"1","label":"按时"},{"name":"2","label":"超时"}]

          this.superviseStateOptions = []
          this.$commonJs.filterDataDict("superviseState",this.superviseStateOptions )
          treeDataList({name:"hazardBClassify"}).then(res=>{
            if(res.code==200){
              this.hazardBClassifyList = res.data
            }
          })


        },
        mounted(){
            this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
        }
    }
</script>

<style lang="scss" scoped>
    .table-all {
        display: flex;
        flex-direction: column;
        height: 100%;

    .search-box {
        padding-bottom: 6px;
    }

    .table-box {
        padding-top: 10px;
        flex: 1;
        display: flex;
        flex-direction: column;

    .table-main {
        flex: 1;
        overflow: auto;
    }

    .table-page {
        // padding-top: 10 px;
        // padding-bottom: 10 px;
    }

    ::v-deep .pagination-container {
        text-align: right;
    }

    }
    }
</style>
